package com.jams.goodox.activity.qa.teacher;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.jams.goodox.BaseActivity;
import com.jams.goodox.BuildConfig;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.home.HomeActivity;
import com.jams.goodox.activity.parent.ParentQuestionAnswerDetailActivity;
import com.jams.goodox.activity.qa.parent.UploadQuestionActivity;
import com.jams.goodox.net.services.LoginService;
import com.jams.goodox.utils.StatusBarCompat;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 向他提问
 */
public class AskHeActivity extends BaseActivity{

    private static final String TAG = AskHeActivity.class.getSimpleName();
    @Bind(R.id.content)
    EditText content;

    @Bind({R.id.submm_btn})
    TextView submm_btn;

    @Bind(R.id.radiogroup)
    RadioGroup radiogroup;

    @Bind(R.id.indicate)
    TextView indicate;

    private int isPublic = 1 ;
    private int teacherId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_askhe;
    }

    @Override
    protected void init() {

        StyleUtil.titleBackKey(this, "向Ta提问");
        StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.main_color));//沉侵式头部

        teacherId = getIntent().getIntExtra("teacherId",-1);

        submm_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadQuestion();
            }
        });

        radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId == R.id.publicCB){
                    isPublic = 1;
                } else {
                    isPublic = 0;
                }
            }
        });

        content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                int countTx = 0;
                if(!TextUtils.isEmpty(s)){
                    countTx = s.length();
                    indicate.setText(countTx + "/150");
                }

            }
        });
    }


    //提交问题
    private void uploadQuestion() {

//        if(TextUtils.isEmpty(title.getText())){
//            ToastUtil.show("请输入标题");
//            return;
//        }

        if(TextUtils.isEmpty(content.getText())){
            ToastUtil.show("请输入问题内容");
            return;
        }

        Map<String,RequestBody> params = new HashMap<>();
        params.put("sign", RequestBody.create(MediaType.parse("multipart/form-data"), "test"));
        params.put("uuid", RequestBody.create(MediaType.parse("multipart/form-data"), "5617222222"));
        params.put("version", RequestBody.create(MediaType.parse("multipart/form-data"), BuildConfig.VERSION_NAME));
        params.put("accessToken", RequestBody.create(MediaType.parse("multipart/form-data"), SePref.getToken()));

        StringBuilder pData = new StringBuilder();
        pData.append("\"memberId\":" + SePref.getId());
        pData.append(",\"teacherId\":" + teacherId);
        pData.append(",\"descr\":" + content.getText().toString());
        pData.append(",\"isPublic\":" + isPublic);

        params.put("requestData", RequestBody.create(MediaType.parse("multipart/form-data"), "{" + pData.toString() + "}"));

//        File files = new File("test");
//        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), files);
//        MultipartBody.Part filePart = MultipartBody.Part.createFormData("files", files.getName(), requestFile);

        // 执行请求
        Call<ResponseBody> call = createCallService(LoginService.class).addQuestion(params,null);
        showLoading();
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call,
                                   Response<ResponseBody> response) {
                misLoading();
                try {
                    String data = response.body().string();
                    Log.d(TAG, "uploadQa data = " + data);

                    JSONObject jsonObject = new JSONObject(data);

                    if(200 == jsonObject.getInt("code") ){
                        ToastUtil.show("问题提交成功");

//                        Intent  intent = new Intent(AskHeActivity.this, ParentQuestionAnswerDetailActivity.class);
//                        startActivity(intent);
                        finish();

                    }else {
                        if(jsonObject.has("error")){
                            ToastUtil.show("error:" + jsonObject.getString("error") );
                        }else {
                            ToastUtil.show("网络异常！" );
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                misLoading();
                Log.d("Upload error:", t.getMessage());
            }
        });

    }


}
